from ntpath import join
from tqdm import trange

from sqlalchemy import func
log_path = "../build/nemu.log"

lines = []
with open(log_path, "r", encoding="utf8") as f:
    lines = [l for l in f.readlines() if 'FTRACE' in l]
# funs = [l[l.index('<')+1:l.rindex('>')] for l in lines]
funs = [l.split()[-1].split('+')[0].replace('<', '').replace('>', '') for l in lines]
print('entry:', funs[0])

counter = {}
for f in funs:
    if f not in counter:
        counter[f] = 1
    else:
        counter[f] = counter[f] + 1

hot_call_list = []
for f in counter:
    hot_call_list.append((f, counter[f]))

list.sort(hot_call_list, key=lambda x: x[1], reverse=True)
print('Hot calls:', hot_call_list[:10])

# trace = {
#     funs[0]: {}
# }
paths = []
path_now = []

def parse_trace(s: str):
    global path_now
    # if s not in path_now:
    #     if len(path_now) != 0:
    #         path_now.append(s)
    #     else:
    #         paths.append(path_now)
    #         path_now = [*path_now[:-1], s]
    if len(path_now) == 0:
        path_now.append(s)
    else:
        if path_now[-1] != s:
            if len(path_now) >= 2:
                # if path_now[-2] == s:
                if s in path_now:
                    # return from sub-function
                    if len(paths) == 0 or paths[-1] != path_now:
                        paths.append([*path_now])
                    path_now = path_now[:-1]
                else:
                    # enter new function
                    path_now.append(s)
            else:
                path_now.append(s)
            
    

for i in trange(len(funs)):
    parse_trace(funs[i])

print(paths[:10])

with open("ftrace.log", 'w', encoding='utf8') as f:
    last_write_len = -1
    for p in paths:
        if len(p) == last_write_len - 1:
            last_write_len = len(p)
            continue
        f.write('/'.join(p).replace("info/kernel_entry/start_kernel/", "") + '\n')
        last_write_len = len(p)
        # if len(p) < 4:
        #     # f.write('/'.join(p).replace("info/kernel_entry/start_kernel/", "") + '\n')
        #     f.write('/'.join(p) + '\n')
        # else:
        #     f.write('.../' + '/'.join(p[-4:]) + '\n')